// pages/AudioSharing/AudioSharing.js
const Controller = require('../controllers/controllers').controller
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    showPhoneIcon: false,
    current: 0,
    limitNum: 0,
    limitTextInput: '',
    limitTextInput3: '',
    width: 600,
    height: 900,
    type: '', //1是栏目，2是合辑，3是音频
    titleArr: ['栏目分享', '合辑分享', '音频分享', '达人榜分享页'],
    currentTypeArr: ['栏目', '合辑', '音频','达人榜'],
    title: '分享',
    template: {}, //海报图片生成配置
    template2: {}, //海报图片生成配置
    template3: {}, //海报图片生成配置
    userInfo: {},
    telephone: '', //手机号码
    imageArr: [],
    templateImg1:'',//海报生成的图片
    templateImg2:'',//海报生成的图片
    templateImg3:'',//海报生成的图片
    cavImg: 'https://tse1-mm.cn.bing.net/th/id/OIP.bNNaDh0yqigvzZYSCSne_AHaKP?pid=Api&rs=1',
    logo: 'https://youyang-cdn.mdshuzhi.com/upload/pic_logo@2x.png',
    QRCode: 'https://youyang-cdn.mdshuzhi.com/upload/youyang_or.png', //二维码图片
    options: {},
    defaultFix: false,
    userNameLeft: 250,
    userNameLeft2: 220,
    hasLenLeft:240,
    currentType: '',
    type:0,
    TalentLeft: 230,
    TalentLeft1: 270,
    fingerImg: 'http://youyangfm.leaf-tech.net:8081/static/miniprogram/1.png',
    istipsnext:true,
    isfirsttips:false,
    topbg:'',
    bottombg:'',
    bgImg1:'',
    bgImg2:'',
    bgImg3:'',
    bgtype:2,
  },
  timer: null,
  // 输入个性文字
  limitTextInput(e) {
    let val = e.detail.value
    let limitNum = val.length
    let that = this
    console.log('输入个性文字', limitNum)

    if (limitNum < 21) {
      that.setData({
        limitTextInput: "“" + val + "”",
        limitTextInput3: "『" + val + "』",
        limitNum
      })
      if (that.timer) {
        clearTimeout(that.timer)
      }
      that.timer = setTimeout(() => {
        that.makeShare(1);
        that.makeShare(2);
        that.makeShare(3);
      }, 300)
      return
    }

  },
  // 展示手机icon
  showPhoneIcon(e) {
    console.log('展示手机icon', e, (this.data.width / 2) - 100)
    let telephone = wx.getStorageSync('telephone') || ''
    let showPhoneIcon = !this.data.showPhoneIcon
    let that = this
    if(this.data.userInfo.nick.length > 6){
      this.setData({
        hasLenLeft:260
      })
    }else if(this.data.userInfo.nick.length<=4){
      this.setData({
        hasLenLeft:210
      })
    }
    // showPhoneIcon false为选择显示手机号
    this.setData({
      showPhoneIcon,
      telephone: !this.data.showPhoneIcon ? ' | ' + telephone : '',
      userNameLeft: 200, //设置名字的离左边的距离
      userNameLeft2: !this.data.showPhoneIcon ? 150 : 200,
    })
    if (this.timer) {
      clearTimeout(this.timer)
    }
    this.timer = setTimeout(() => {
      that.getDraw()
    }, 300)
  },
  // 轮播图
  swiperHandel(e) {
    // console.log(e.detail)
    this.setData({
      current: e.detail.current
    })
    // if(e.detail.current==1){
    //   this.setData({bgtype:3})

    // }
    // if(e.detail.current==2){
    //   this.setData({bgtype:1})

    // }
    // if(e.detail.current==0){
    //   this.setData({bgtype:2})

    // }
  },
  // 保存图片
  saveImgBtn() {
    console.log('保存图片')
    let saveImg = '';
    let current = this.data.current
    wx.showLoading({
      title: '保存中',
      mask: true,
    })
    if(current == 0){
      saveImg = this.data.templateImg1
    }else if(current == 1){
      saveImg = this.data.templateImg2
    }else if(current == 2){
      saveImg = this.data.templateImg3
    }
    console.log('current',current,'saveImg',saveImg)
    app.saveImg(saveImg)
    app.updateScore(7)

  },
  // 绘制成功
  onImgOK1(res) {
    console.log('绘制成功', res)
    wx.hideLoading()
    this.setData({
      templateImg1:res.detail.path
    })
  },
  onImgOK2(res) {
    console.log('绘制成功', res)
    wx.hideLoading()
    this.setData({
      templateImg2:res.detail.path
    })
  },onImgOK3(res) {
    console.log('绘制成功', res)
    wx.hideLoading()
    this.setData({
      templateImg3:res.detail.path
    })
  },
  // 绘制失败
  onImgErr(err) {
    console.log('绘制失败', err)

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    /* 
      options 需要接收 
          path 上一个页面的路径
          type 栏目等的类型
    */
    let id = options.id; //音频id
    console.log('类型', options, id, this.data.titleArr[options.type - 1],getCurrentPages())
    if (options.type != 4) {
      this.setData({
        currentType: this.data.currentTypeArr[Number(options.type) - 1]
      })
    }else{
      // 设置分享字体的左边距
      this.setData({
        TalentLeft: 180,
        TalentLeft1:210
      })
    }
    if(options.type){
      this.setData({
        type:Number(options.type)-1
      })
    }
    this.setData({
      options,
      title: this.data.titleArr[options.type - 1]
    })

    if(options.img){
      this.setData({
        cavImg: options.img, //海报图片
        userInfo: wx.getStorageSync('userInfo')
      })
      this.makeShare(1);
      this.makeShare(2);
      this.makeShare(3);
    }else{
      Controller.shareImg({
        type: options.type, //类别
        token: wx.getStorageSync('logintoken')
      })
      .then(res => {
        console.log('shareImg', res)
        if (res.code == 0) {
          this.setData({
            cavImg: res.data.baseData, //海报图片
            userInfo: wx.getStorageSync('userInfo')
          })
          // 获取二维码
          this.makeShare(1);
          this.makeShare(2);
          this.makeShare(3);
        }
      })
    }
    if(app.globalData.firsttips){
      this.firsttips()
    }
  },
  path(){
    var options=this.data.options;
    var path="/pages/Index/Index"
    if(options.type==1){
      path="/pages/Exclusive/Exclusive?id="+options.audioId
    }
    if(options.type==2){
      path="/pages/Album/Detail/Detail?id="+options.audioId
    }
    if(options.type==3){
      path="/pages/Playing/Playing?audioId="+options.audioId
    }
    if(options.type==4){
      path="/pages/Talent/Talent"
    }
    return path
  },
  path2(){
    var options=this.data.options;
    var path="pages/Index/Index"
    if(options.type==1){
      path="pages/Exclusive/Exclusive"
    }
    if(options.type==2){
      path="pages/Album/Detail/Detail"
    }
    if(options.type==3){
      path="pages/Playing/Playing"
    }
    if(options.type==4){
      path="pages/Talent/Talent"
    }
    return path
  },
  cutString(str,len){
    var length = 0;
    var string = '';
   
    if (len > str.length) {
      return str;
    }else{
      for (var i = 0; i < len; i++) {
        var a = str.charAt(i);
   
        length++;
   
        if(escape(a).length > 4){
          // length ++;  // html中开启
        }
   
        string = string.concat(a);
   
        if (length >= len) {
          string = string.concat("...");
          return string;
        }
      }
    }
  },


  // 绘画海报
  getDraw() {
    wx.showLoading({
      title: '正在努力生成中',
    })
    this.setData({
      template: {
        background: '#fff',
        width: this.data.width + 'rpx',
        height: this.data.height + 'rpx',
        views: [{
            type: 'image',
            url: this.data.bgImg1, 
            css: {
              width:'600rpx',
              height:'900rpx'
            },
          },{
            type: 'text',
            text: this.data.limitTextInput, //你想输入的文字
            css: {
              width:'540rpx',
              maxLines: "2",
              lineHeight: "50rpx",
              bottom: '330rpx',
              left: '30rpx',
              fontSize: '40rpx',
              color: "#fff",
              fontWeight: "bold"
            },
          }, {
            type: 'text',
            text: this.data.userInfo.nick  + this.data.telephone, //用户名
            css: {
              width:'480rpx',
              maxLines:'1',
              lineHeight: "25rpx",
              bottom: '240rpx',
              left: '90rpx',
              fontSize: '20rpx',
              color: "#A8ACBB",
            },
          }, {
            type: 'text',
            text: '为你分享' + this.data.currentType, //为你分享歌曲
            css: {
              lineHeight: "25rpx",
              bottom: '200rpx',
              left: '90rpx',
              fontSize: '24rpx',
              color: "#323232",
            },
          }, {
            type: 'text',
            text: '《' + this.cutString(this.data.options.title,10) + '》', //歌曲名称
            css: {
              lineHeight: "25rpx",
              bottom: '200rpx',
              left: this.data.TalentLeft+'rpx',
              fontSize: '24rpx',
              color: "#C57F6F",
            },
          }, {
            type: 'text',
            text: '有氧FM·音频分享',
            css: {
              left: "200rpx",
              bottom: '50rpx',
              fontSize: '20rpx',
              color: "#A8ACBB",
            },
          }
        ],
      },
      template2: {
        background:'#fff',
        width: this.data.width + 'rpx',
        height: this.data.height + 'rpx',
        views: [{
            type: 'image',
            url: this.data.bgImg2, 
            css: {
              width:'600rpx',
              height:'900rpx'
            },
          },{
          type: 'text',
          text: '有氧FM·音频分享', //有氧FM·音频分享
          css: {
            width: this.data.width + 'rpx',
            top: '30rpx',
            left: '245rpx',
            fontSize: '20rpx',
            color: "#323232"
          },
        },{
          type: 'text',
          text: this.data.limitTextInput, //输入内容
          css: {
            width: '440rpx',
            maxLines: 2,
            lineHeight: "35rpx",
            top: '620rpx',
            left: this.data.width / 2 - 220 + 'rpx',
            fontSize: '30rpx',
            color: "#323232",
            textAlign: 'center',
            fontWeight: "bold"
          },
        }, {
          type: 'text',
          text: this.data.userInfo.nick + this.data.telephone, //用户名
          css: {
            width:"500rpx",
            height: '20rpx',
            maxLines:'1',
            left: '50rpx',
            top: '795rpx',
            fontSize: '20rpx',
            color: "#A8ACBB",
            textAlign: "center"
          },
        },  {
          type: 'text',
          text: '为你分享' + this.data.currentType, //为你分享歌曲
          css: {
            height: '40rpx',
            left: '50rpx',
            maxLines: 1,
            width:"500rpx",
            top: '830rpx',
            lineHeight:"26rpx",
            fontSize: '24rpx',
            color: "#323232",
            textAlign: 'center',
          },
        }, {
          type: 'text',
          text: "《" + this.cutString(this.data.options.title,18) + "》", //歌曲名称
          css: {
            top: '860rpx',
            width:"500rpx",
            lineHeight:"26rpx",
            left: '50rpx',
            fontSize: '24rpx',
            color: "#C57F6F",
            textAlign: 'center',
          },
        }],
      },
      template3: {
        background: '#fff',
        width: this.data.width + 'rpx',
        height: this.data.height + 'rpx',
        views: [{
            type: 'image',
            url: this.data.bgImg3, 
            css: {
              width:'600rpx',
              height:'900rpx'
            },
          },{
          type: 'text',
          text: '有氧FM·音频分享', //有氧FM·音频分享
          css: {
            width: this.data.width + 'rpx',
            top: '30rpx',
            left: '245rpx',
            fontSize: '20rpx',
            color: "#fff"
          },
        }, {
          type: 'text',
          text: this.data.limitTextInput3, //你想输入的文字
          css: {
            width: '380rpx',
            maxLines: 2,
            lineHeight: "50rpx",
            top: '630rpx',
            left: '25rpx',
            fontSize: '36rpx',
            color: "#323232",
            fontWeight: "bold"
          },
        }, {
          type: 'text',
          text: this.data.userInfo.nick + this.data.telephone, //用户名
          css: {
            width:'330rpx',
            maxLines:1,
            top: '790rpx',
            left: '90rpx',
            fontSize: '18rpx',
            color: "#A8ACBB",
          },
        },  {
          type: 'text',
          text: '为你推荐' + this.data.currentType, //为你推荐
          css: {
            top: '830rpx',
            left: '90rpx',
            fontSize: '22rpx',
            color: "#323232",
          },
        }, {
          type: 'text',
          text: "《" + this.cutString(this.data.options.title,7) + "》", //歌名
          css: {
            top: '830rpx',
            width:"220rpx",
            left: this.data.TalentLeft + 'rpx',
            fontSize: '22rpx',
            color: "#E66D4D",
          },
        }],
      }
    })
  },
  onPageScroll: function (e) { // 获取滚动条当前位置
    if (e.scrollTop > 20) {
      this.setData({
        defaultFix: true
      })
    } else {
      this.setData({
        defaultFix: false
      })
    }
    let query = wx.createSelectorQuery()
    query.select('#audioShare').boundingClientRect((rect) => {
      let top = rect.top;
      if (top < this.data.navHeight) {
        this.setData({
          isFixedTop: true
        })
      } else {
        this.setData({
          isFixedTop: false
        })
      }
    }).exec()
  },
  // 生成二维码
  /* 
    参数：
    path：二维码扫描后跳转的页面
    scene：参数  如 a=3
  */
  // makeShareImg(options) {
  //   let path=this.path2()
  //   var options=this.data.options;
  //   let data={source: 1,path}
  //   if(options.audioId){
  //     data.scene=options.audioId
  //   }else{
  //     data.scene=1
  //   }

  //   Controller.makeShareImg(data)
  //     .then(res => {
  //       console.log('生成二维码', res)
  //       if (res.code == 0) {
  //         let QRCode = res.data.baseData ? res.data.baseData : 'https://youyang-cdn.mdshuzhi.com/upload/youyang_or.png'
  //         this.setData({
  //           QRCode
  //         })
  //         this.getDraw()
  //       }
  //     })
  // },

  makeShare(type) {
    let path=this.path2()
    var options=this.data.options;
    let data={source: 1,path}
    if(options.audioId){
      data.scene=options.audioId
    }else{
      data.scene=1
    }
    data.type=type || this.data.bgtype
    data.itemImg=this.data.cavImg
    Controller.makeShare(data).then(res => {
      if (res.code == 0) {
        let bgImg = res.data.baseData
        if(data.type==3){
          this.setData({
            bgImg2:bgImg
          })
        }else if(data.type==1){
          this.setData({
            bgImg3:bgImg
          })
        }else{
          this.setData({
            bgImg1:bgImg
          })
        }

        if(this.data.bgImg1 && this.data.bgImg2 && this.data.bgImg3){
          this.getDraw()
        }
      }
    })
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  onReady(){

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    console.log('分享按钮', e)
    let title = this.data.titleArr[this.data.type] || '音频分享';
    let imageUrl = this.data.imageArr[0];
    let options = this.data.options
    let path=this.path()
    // // if (e.from == "button") {
      let obj = {
        title,
        path: path,
        success: function (res) {
          console.log('点击页面内的分享按钮--onShareAppMessage分享成功', res)
        },
        fail(err) {
          console.log('点击页面内的分享按钮--onShareAppMessage-fail', err)
        }
      }
      app.updateScore(7)
      return obj
    // }
  },
  onShareTimeline: function(res){
    let title = this.data.titleArr[this.data.type] || '音频分享';
    let imageUrl = this.data.imageArr[0];
    let options = this.data.options
    let path=this.path()
    // // if (e.from == "button") {
      let obj = {
        title,
        path: path,
        imageUrl,
        success: function (res) {
          console.log('点击页面内的分享按钮--onShareAppMessage分享成功', res)
        },
        fail(err) {
          console.log('点击页面内的分享按钮--onShareAppMessage-fail', err)
        }
      }
      app.updateScore(7)
      return obj
    // }
  },
  firsttips(){
    let that=this;
    wx.createSelectorQuery().select('#audioShare').boundingClientRect(function (rect) {
     // 使页面滚动到底部
     wx.pageScrollTo({
       scrollTop: rect.bottom
     })
   }).exec()

    that.setData({
      isfirsttips:true
    })
    app.globalData.firsttips=false
  },
  tipsnext(){
    let that=this;
    that.setData({
      istipsnext:false
    })
  },
  tipsclose(){
    this.setData({
      isfirsttips:false
    })
  },

})